package com.foo.web.controller.common;


import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.*;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.foo.common.core.domain.AjaxResult;
import com.foo.common.utils.StringUtils;
import com.foo.common.utils.file.FileUploadUtils;
import com.foo.web.core.config.UploadFile;
import com.foo.web.core.config.UploadUtil;
import com.foo.web.wechat.config.WechatConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("文件上传")
@Controller
@RequestMapping("/wechat/api/oss")
public class UploadOssApi {


    @Autowired
    private WechatConfig wechatConfig;


    /**
     * 公用单文件上传接口
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation("公用单文件上传接口")
    @PostMapping("/uploadoss")
    @ResponseBody
    public AjaxResult upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multiRequest.getFile("file");
        String path = FileUploadUtils.upload(wechatConfig.getFileUrl(), file);
        File fliePath = new File(wechatConfig.getFileUrl() + path);
        System.gc();

        String aliyunOssPath = FileUploadUtils.aliyunOssUpload(fliePath, wechatConfig.getEndPoint(), wechatConfig.getKeyId(),
                wechatConfig.getKeySecret(), wechatConfig.getBucketName(), wechatConfig.getFileHost(),file.getContentType());
        FileUtil.del(fliePath);
        String  PrefixUrl = "https://"+wechatConfig.getBucketName()+"."+wechatConfig.getEndPoint();
        return AjaxResult.success(PrefixUrl+"/"+ aliyunOssPath);
    }
    /**
     * 多文件
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/uploadFj")
    @ResponseBody
    public AjaxResult uploadFj(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        List<UploadFile> fileList = UploadUtil.getUploadFiles(multiRequest, wechatConfig.getFileUrl(), "JPG");
        Map<String, Object> map = new HashMap<String, Object>();
        response.setContentType("text/xml;charset=UTF-8");
        int i = 0;
        String[] str = new String[fileList.size()];
        for (UploadFile file : fileList) {
            System.out.println("上传文件有：" + file);
            File path = new File(file.getFilePath());
            String bannerpath = FileUploadUtils.aliyunOssUpload(path, wechatConfig.getEndPoint(),
                    wechatConfig.getKeyId(), wechatConfig.getKeySecret(), wechatConfig.getBucketName() ,wechatConfig.getFileHost(),file.getFileType());
            FileUtil.del(path);
            String  PrefixUrl = "https://"+wechatConfig.getBucketName()+"."+wechatConfig.getEndPoint()+"/";
            str[i] = PrefixUrl + bannerpath;
            i++;
        }
        map.put("msg", str);
        String str4 = StringUtils.join(str, ","); // 数组转字符串(逗号分隔)(推荐)
        System.out.println(str4);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        return AjaxResult.success(str4);
    }
    /**
     * 删除对象存储文件
     * @param ids
     * @return
     */
    @PostMapping("/removeoss")
    @ResponseBody
    public AjaxResult remove(String ids) {
        String  PrefixUrl = "https://"+wechatConfig.getBucketName()+"."+wechatConfig.getEndPoint()+"/";
        String ossUrl = ids.substring(PrefixUrl.length(), ids.length());
        return AjaxResult.success(delOSS(ossUrl));
    }
    public AjaxResult delOSS(String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(wechatConfig.getEndPoint(), wechatConfig.getKeyId(), wechatConfig.getKeySecret());
        // 删除文件。
        ossClient.deleteObject(wechatConfig.getBucketName(), objectName);
        // 关闭OSSClient。
        ossClient.shutdown();
        return AjaxResult.success();
    }

    @GetMapping("/getsing")
    @ResponseBody
    protected AjaxResult getSignature(){

        String endpoint = wechatConfig.getEndPoint();
        String accessId =  wechatConfig.getKeyId();
        String accessKey =  wechatConfig.getKeySecret();
        try {
            OSSClient ossClient = new OSSClient(endpoint,accessId,accessKey);
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, wechatConfig.getFileHost());//根据参数dir计算的policy，如果和前端uploadfile中参数key的相应字段不一致的话是会报错的

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes();
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            ossClient.shutdown();//业务完成一定要调用shutdown

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("accessId",accessId);
            map.put("policy", encodedPolicy);
            map.put("signature", postSignature);
            map.put("dir", wechatConfig.getFileHost());
            map.put("host","https://"+wechatConfig.getBucketName()+"."+endpoint+"/");
            return  AjaxResult.success(map);

        } catch (Exception e) {
            //Assert.fail(e.getMessage());
        }

        return null;
    }
}
